{% extends "base.html" %}

{% block title %}告警管理 - XCQuant{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">告警管理</h3>
                    <div class="card-tools">
                        <button type="button" class="btn btn-sm btn-primary" onclick="refreshAlerts()">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- 告警过滤器 -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <select class="form-control" id="alertStatus">
                                <option value="active">活跃告警</option>
                                <option value="resolved">已解决</option>
                                <option value="all">全部</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select class="form-control" id="alertLevel">
                                <option value="">全部级别</option>
                                <option value="critical">严重</option>
                                <option value="warning">警告</option>
                                <option value="info">信息</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <input type="number" class="form-control" id="alertLimit" placeholder="显示数量" value="100">
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary" onclick="filterAlerts()">筛选</button>
                        </div>
                    </div>

                    <!-- 告警列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped" id="alertsTable">
                            <thead>
                                <tr>
                                    <th>级别</th>
                                    <th>标题</th>
                                    <th>消息</th>
                                    <th>状态</th>
                                    <th>创建时间</th>
                                    <th>解决时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 告警数据将通过JavaScript加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 告警详情模态框 -->
<div class="modal fade" id="alertDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">告警详情</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="alertDetailContent">
                <!-- 详情内容 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="resolveAlert()">标记为已解决</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentAlerts = [];
let selectedAlertId = null;

// 页面加载时初始化
$(document).ready(function() {
    loadAlerts();
    
    // 每30秒自动刷新
    setInterval(loadAlerts, 30000);
});

// 加载告警数据
function loadAlerts() {
    const status = $('#alertStatus').val();
    const level = $('#alertLevel').val();
    const limit = $('#alertLimit').val();
    
    let url = '/api/alerts?status=' + status + '&limit=' + limit;
    if (level) {
        url += '&level=' + level;
    }
    
    $.get(url)
        .done(function(response) {
            if (response.success) {
                currentAlerts = response.data.alerts;
                renderAlertsTable();
            } else {
                showError('加载告警数据失败: ' + response.error);
            }
        })
        .fail(function() {
            showError('网络错误，无法加载告警数据');
        });
}

// 渲染告警表格
function renderAlertsTable() {
    const tbody = $('#alertsTable tbody');
    tbody.empty();
    
    if (currentAlerts.length === 0) {
        tbody.append('<tr><td colspan="7" class="text-center">暂无告警数据</td></tr>');
        return;
    }
    
    currentAlerts.forEach(function(alert) {
        const levelBadge = getLevelBadge(alert.level);
        const statusBadge = getStatusBadge(alert.status);
        const createdAt = new Date(alert.created_at).toLocaleString();
        const resolvedAt = alert.resolved_at ? new Date(alert.resolved_at).toLocaleString() : '-';
        
        const row = `
            <tr>
                <td>${levelBadge}</td>
                <td>${alert.title}</td>
                <td>${alert.message.substring(0, 50)}${alert.message.length > 50 ? '...' : ''}</td>
                <td>${statusBadge}</td>
                <td>${createdAt}</td>
                <td>${resolvedAt}</td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="showAlertDetail('${alert.id}')">
                        <i class="fas fa-eye"></i>
                    </button>
                </td>
            </tr>
        `;
        tbody.append(row);
    });
}

// 获取级别徽章
function getLevelBadge(level) {
    const badges = {
        'CRITICAL': '<span class="badge badge-danger">严重</span>',
        'WARNING': '<span class="badge badge-warning">警告</span>',
        'INFO': '<span class="badge badge-info">信息</span>'
    };
    return badges[level] || '<span class="badge badge-secondary">' + level + '</span>';
}

// 获取状态徽章
function getStatusBadge(status) {
    const badges = {
        'ACTIVE': '<span class="badge badge-danger">活跃</span>',
        'RESOLVED': '<span class="badge badge-success">已解决</span>'
    };
    return badges[status] || '<span class="badge badge-secondary">' + status + '</span>';
}

// 显示告警详情
function showAlertDetail(alertId) {
    const alert = currentAlerts.find(a => a.id === alertId);
    if (!alert) return;
    
    selectedAlertId = alertId;
    
    const content = `
        <div class="row">
            <div class="col-md-6">
                <strong>ID:</strong> ${alert.id}
            </div>
            <div class="col-md-6">
                <strong>级别:</strong> ${getLevelBadge(alert.level)}
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-md-6">
                <strong>状态:</strong> ${getStatusBadge(alert.status)}
            </div>
            <div class="col-md-6">
                <strong>创建时间:</strong> ${new Date(alert.created_at).toLocaleString()}
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-12">
                <strong>标题:</strong> ${alert.title}
            </div>
        </div>
        <div class="row mt-2">
            <div class="col-12">
                <strong>消息:</strong><br>
                <div class="alert alert-light">${alert.message}</div>
            </div>
        </div>
        ${alert.tags && alert.tags.length > 0 ? `
        <div class="row mt-2">
            <div class="col-12">
                <strong>标签:</strong><br>
                ${alert.tags.map(tag => `<span class="badge badge-secondary mr-1">${tag}</span>`).join('')}
            </div>
        </div>
        ` : ''}
        ${alert.data ? `
        <div class="row mt-2">
            <div class="col-12">
                <strong>附加数据:</strong><br>
                <pre class="bg-light p-2">${JSON.stringify(alert.data, null, 2)}</pre>
            </div>
        </div>
        ` : ''}
    `;
    
    $('#alertDetailContent').html(content);
    $('#alertDetailModal').modal('show');
}

// 刷新告警
function refreshAlerts() {
    loadAlerts();
}

// 筛选告警
function filterAlerts() {
    loadAlerts();
}

// 解决告警
function resolveAlert() {
    if (!selectedAlertId) return;
    
    // 这里应该调用API来解决告警
    // 暂时只是关闭模态框并刷新数据
    $('#alertDetailModal').modal('hide');
    setTimeout(loadAlerts, 500);
}

// 显示错误消息
function showError(message) {
    // 可以使用toast或其他方式显示错误
    console.error(message);
    alert(message);
}
</script>
{% endblock %}